import HeaderNav from "@/components/header-nav"
import FooterNav from "@/components/footer-nav"
import { Grid, Image, List, Modal, Button, Badge } from 'antd-mobile'
import {
  BillOutline, BankcardOutline, FillinOutline,
  FileOutline, UnorderedListOutline,
  PayCircleOutline,
  BellOutline,
  SearchOutline,
  UserCircleOutline,
  EditSOutline,
  CheckOutline,
  UserContactOutline,
  LockOutline,
  CheckCircleFill
} from 'antd-mobile-icons'
import { showSuccessToast } from '@/utils/customToast'
import defaultAvatarIcon from '@/assets/icons/sex-secrecy.svg'
import styles from "./index.module.less"
import { useEffect, useState } from "react"
const { getUserInfo, getSettings, getMemberLevel, getMemberLevelList } = $globalServicer('My')
const { setNotificationUnread } = $globalReduxAction('common')
import dayjs from 'dayjs'
import Cookies from 'js-cookie'
const My = () => {
  const [userInfo, setUserInfo] = useState(null)
  const [visible, setVisible] = useState(false)
  const [inviteVisible, setInviteVisible] = useState(false)
  const [memberList, setMemberList] = useState([])
  const [vipContent, setVipContent] = useState([])
  const [memberModalVisible, setMemberModalVisible] = useState(false)
  const [currentMemberInfo, setCurrentMemberInfo] = useState(null)
  const customNavigate = $globalNavigate()
  const [inviteUrl, setInviteUrl] = useState('')
  const [activeCardIndex, setActiveCardIndex] = useState(0)
  const [touchStart, setTouchStart] = useState(0)
  const [touchEnd, setTouchEnd] = useState(0)

  const handleCopy = async () => {
    if (!inviteUrl) {
      toast({
        title: "Error",
        description: "Please enter some text to copy.",
        variant: "destructive",
      })
      return
    }

    const copyStr = inviteUrl + ' 分享好友立即注册获得奖励'
    try {
      if (navigator.clipboard && navigator.clipboard.writeText) {
        await navigator.clipboard.writeText(copyStr)
        showSuccessToast('复制成功')
      } else {
        const textArea = document.createElement('textarea')
        textArea.value = copyStr
        document.body.appendChild(textArea)
        textArea.select()
        document.execCommand('copy')
        document.body.removeChild(textArea)
        showSuccessToast('复制成功')
      }
    } catch (err) {
      console.error('复制失败: ', err);
    }
  };
  const logout = () => {
    localStorage.clear('')
    const allCookies = Cookies.get();
    console.log(`allCookies`, allCookies)
    // 遍历所有cookies并逐个删除
    // for (const cookieName in allCookies) {
    //   Cookies.remove(cookieName);
    //   Cookies.remove(cookieName, { path: '/' });
    // }

    Object.keys(allCookies).forEach(cookieName => {
      // 移除不同路径和域名下的 cookie
      Cookies.remove(cookieName);
      Cookies.remove(cookieName, { path: '/' });
      Cookies.remove(cookieName, { path: '', domain: window.location.hostname });
      Cookies.remove(cookieName, { path: '/', domain: window.location.hostname });

      // 如果有子域名，也需要清除
      const domain = window.location.hostname;
      if (domain.indexOf('.') !== -1) {
        const mainDomain = domain.substring(domain.indexOf('.'));
        Cookies.remove(cookieName, { path: '/', domain: mainDomain });
      }
    });
    customNavigate('/login')
    // if (element) {
    //   element.click()
    // }
    // setTimeout(() => {
    //   customNavigate('/login')  
    // }, 0)
  }
  const fetchUserInfo = () => {
    getUserInfo().then(res => {
      let url = window.location.href.split('#')[0] + '#/register?invite_code=' + res?.user?.id
      setInviteUrl(url)
      setUserInfo(res)
      
      // 检查用户信息中的is_read字段，与登录页面保持一致
      if (res && res.user && res.user.is_read !== undefined) {
        // 如果is_read字段为0，显示小红点
        setNotificationUnread(res.user.is_read === 0)
      }
    })
  }

  useEffect(() => {
    fetchUserInfo()
    getMemberLevelList().then(res => {
      setMemberList(res)
    })
  }, [])

  const handleTouchStart = (e) => {
    setTouchStart(e.targetTouches[0].clientX)
  }

  const handleTouchMove = (e) => {
    setTouchEnd(e.targetTouches[0].clientX)
  }

  const handleTouchEnd = () => {
    if (touchStart - touchEnd > 75) {
      // 向左滑动
      setActiveCardIndex(prev => prev < memberList.length - 1 ? prev + 1 : prev)
    }

    if (touchStart - touchEnd < -75) {
      // 向右滑动
      setActiveCardIndex(prev => prev > 0 ? prev - 1 : prev)
    }
  }
  const handleVipContent = (content) => {
    if (content?.length && content.indexOf("\r\n")) {
      content = content.split("\r\n");
    } else {
      content = [content];
    }
    return content
  }

  // 获取当前会员信息
  const getCurrentMemberInfo = () => {
    if (!userInfo?.user?.level_id || !memberList?.length) {
      return null
    }
    return memberList.find(member => member.id === userInfo.user.level_id)
  }

  // 处理会员等级点击
  const handleMemberLevelClick = () => {
    const memberInfo = getCurrentMemberInfo()
    if (memberInfo) {
      // 处理 benefits 字段，确保是数组格式
      const processedMemberInfo = {
        ...memberInfo,
        benefits: handleVipContent(memberInfo.benefits)
      }
      setCurrentMemberInfo(processedMemberInfo)
      setMemberModalVisible(true)
    }
  }

  // 检查图片是否为webp格式
  const isWebpImage = (imageUrl) => {
    if (!imageUrl) return false;
    return imageUrl.toLowerCase().endsWith('.webp');
  }

  return (
    <div className={styles.warp}>
      <main className={styles.main}>
        {/* 用户信息头部 */}
        <div className={styles.userHeader}>
          <div className={styles.avatarContainer}>
            {userInfo?.user?.cover && isWebpImage(userInfo.user.cover) ? (
              <Image
           WY   className={styles.avatar}
                src={userInfo.user.cover}
                fit='cover' />
            ) : (
              <div className={styles.defaultAvatar}>
                <img 
                  src={defaultAvatarIcon} 
                  alt="默认头像" 
                  className={styles.defaultAvatarIcon}
                />
              </div>
            )}
          </div>
          <div className={styles.userInfo}>
            <p className={styles.userName}>{userInfo?.user?.name || '加载中...'}</p>
            <p className={styles.userId}>ID: WY{userInfo?.user?.id || '加载中...'}</p>
          </div>
          <a className={styles.editProfile} onClick={() => customNavigate('/userInfo')}>
            <span className={styles.editText}>编辑资料</span>
            <span className={styles.chevronIcon}>chevron_right</span>
          </a>
        </div>

        {/* 积分和会员等级卡片 */}
        <div className={styles.statsCard}>
          <div className={styles.statsItem}>
            <p className={styles.statsValue}>{userInfo?.user?.diamond_balance || 128}</p>
            <p className={styles.statsLabel}>积分余额</p>
          </div>
          <div className={styles.statsDivider}></div>
          <div className={styles.statsItem} onClick={handleMemberLevelClick} style={{ cursor: 'pointer' }}>
            <p className={`${styles.memberLevel} ${getCurrentMemberInfo() ? styles.memberLevelActive : ''}`}>
              {getCurrentMemberInfo()?.title || '普通用户'}
            </p>
            <p className={styles.memberLabel}>会员等级</p>
            {getCurrentMemberInfo() && (
              <p className={`${styles.memberExpireTime} ${styles.memberLevelActive}`}>
                到期时间: {getCurrentMemberInfo()?.level_expiration_time ? getCurrentMemberInfo().level_expiration_time.split(' ')[0] : '2024-12-31'}
              </p>
            )}
          </div>
        </div>

        {/* 功能菜单组1 */}
        <div className={styles.menuGroup}>
          <a className={styles.menuItem} onClick={() => customNavigate('/recharge')}>
            <div className={styles.menuLeft}>
              <span className={styles.menuIcon}>workspace_premium</span>
              <span className={styles.menuText}>充值服务</span>
            </div>
            <span className={styles.chevronIcon}>chevron_right</span>
          </a>
          <a className={styles.menuItem} onClick={() => customNavigate('/inviter')}>
            <div className={styles.menuLeft}>
              <span className={styles.menuIcon}>group_add</span>
              <span className={styles.menuText}>邀请新人</span>
            </div>
            <span className={styles.chevronIcon}>chevron_right</span>
          </a>
        </div>

        {/* 功能菜单组2 */}
        <div className={styles.menuGroup}>
          <a className={styles.menuItem} onClick={() => customNavigate('/updatePassWord')}>
            <div className={styles.menuLeft}>
              <span className={styles.menuIcon}>lock_reset</span>
              <span className={styles.menuText}>修改密码</span>
            </div>
            <span className={styles.chevronIcon}>chevron_right</span>
          </a>
          <a className={styles.menuItem} onClick={() => customNavigate('/help')}>
            <div className={styles.menuLeft}>
              <span className={styles.menuIcon}>help_outline</span>
              <span className={styles.menuText}>帮助详情</span>
            </div>
            <span className={styles.chevronIcon}>chevron_right</span>
          </a>
          <a className={styles.menuItem} onClick={() => customNavigate('/diamondRecord?diamond_balance=' + userInfo?.user?.diamond_balance)}>
            <div className={styles.menuLeft}>
              <span className={styles.menuIcon}>receipt_long</span>
              <span className={styles.menuText}>积分明细</span>
            </div>
            <span className={styles.chevronIcon}>chevron_right</span>
          </a>
        </div>

        {/* 退出登录按钮 */}
        <div className={styles.logoutSection}>
          <a className={styles.logoutButton} onClick={() => logout()}>
            退出登录
          </a>
        </div>
      </main>


      {/* 模态框保持不变 */}
      <Modal
        visible={visible}
        content={<div className={styles.vipContent}>
          {vipContent.map((g, _index) => (
          <div className={styles.benefitItem} key={_index}>
            <CheckCircleFill className={styles.checkIcon} />
            <span key={_index}>{g}</span>
          </div>
        ))}</div>}
        showCloseButton={true}
        onClose={() => {
          setVisible(false)
        }}
      />
      <Modal
        visible={inviteVisible}
        content={<div className={styles.inviteContent}>
          <p className={styles.inviteContentTitle}>我是{userInfo?.user?.name}</p>
          <p className={styles.inviteContentDesc}>截图保存二维码，分享好友立即注册获得奖励</p>
          <div className={styles.inviteContentImg}>
            <img src={`https://api.2dcode.biz/v1/create-qr-code/?size=100x100&data=${encodeURIComponent(inviteUrl)}`} alt="" />
          </div>
          <div className={styles.inviteContentBtn}></div>
          <Button color='primary' size='small' onClick={handleCopy}>复制链接</Button>
        </div>}
        showCloseButton={true}
        onClose={() => {
          setInviteVisible(false)
        }}
      />
      
      {/* 会员等级详情弹窗 */}
      <Modal
        visible={memberModalVisible}
        className="member-modal"
        content={<div className={styles.memberModalContent}>
          <div className={styles.memberModalHeader}>
            <h2 className={styles.memberModalTitle}>会员权益</h2>
            <button className={styles.memberModalClose} onClick={() => setMemberModalVisible(false)}>
              <i className="material-icons">close</i>
            </button>
          </div>
          
          <div className={styles.memberInfoSection}>
            <div className={styles.memberInfoCard}>
              <h3 className={styles.memberInfoTitle}>{currentMemberInfo?.title || 'UR 会员'}</h3>
              <p className={styles.modalMemberExpireTime}>到期时间: {currentMemberInfo?.level_expiration_time ? currentMemberInfo.level_expiration_time.split(' ')[0] : '2024-12-31'}</p>
            </div>
          </div>

          <div className={styles.memberBenefitsSection}>
            <h3 className={styles.sectionTitle}>会员权益</h3>
            <div className={styles.benefitsList}>
              {currentMemberInfo?.benefits && Array.isArray(currentMemberInfo.benefits) ? (
                currentMemberInfo.benefits.map((benefit, index) => (
                  <div key={index} className={styles.benefitItem}>
                    <span className={styles.benefitIcon}>∞</span>
                    <span className={styles.benefitText}>{benefit}</span>
                  </div>
                ))
              ) : (
                <div className={styles.benefitItem}>
                  <span className={styles.benefitIcon}>∞</span>
                  <span className={styles.benefitText}>无限使用所有模型</span>
                </div>
              )}
            </div>
          </div>
        </div>}
        showCloseButton={false}
        onClose={() => {
          setMemberModalVisible(false)
        }}
      />
      
      <FooterNav></FooterNav>
    </div>
  );
};

export default My;
